import { Component, OnInit, OnDestroy } from '@angular/core';
import { MessageService } from 'src/app/core/service/message.service';
import { ApiService, urlService } from 'src/app/core/api';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd';
import { UserInfoService } from 'src/app/core/service';

@Component({
  selector: 'app-setting',
  templateUrl: './setting.component.html',
  styleUrls: ['./setting.scss']
})
export class SettingComponent implements OnInit, OnDestroy {

  private _isVisible = false;
  private _timer;

  url = 'setting';

  isConfirmLoading = false;
  validateForm: FormGroup;
  fromData: any = {
    isDefault: false
  };
  captchaLabel = '发送验证码';

  set isVisible(_isVisible: boolean) {
    this._isVisible = _isVisible;
    if (_isVisible) {
      if (this._timer) {
        clearInterval(this._timer);
      }
      this.captchaLabel = '发送验证码';
    }
  }

  get isVisible() {
    return this._isVisible;
  }

  private _config: any;
  private _data: any;
  private _selTag: any; // 当前选中
  private _altTitle: string;
  private _isEdit: boolean;
  private _user: any;
  private _bool = true;


  updateConfirmValidator(): void {
    Promise.resolve().then(() => this.validateForm.controls.newConfirmPwd.updateValueAndValidity());
  };
  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.newPwd.value) {
      return { confirm: true, error: true };
    };
  };
  confirmationFandValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.newFundPwd.value) {
      return { confirm: true, error: true };
    }
  }

  ngOnInit() {
    this.msg.sendMessage(this.url)
  };

  showModal(name): void {
    name == '修改登陆密码' || name == '修改支付密码' ? this._isEditFn(true, name) : this._isEditFn(false, name);
    this.validateForm.reset();
    this._altTitle = name;
    this.isVisible = true;
    this._selTag = {
      name: name
    };
  };
  private _isEditFn(bool, name): void {
    this._isEdit = bool;
    switch (name) {
      case '修改登陆密码':
        this.validateForm = this.fb.group({
          verifyCode: ['', []],
          newConfirmFundPwd: ['', []],
          newFundPwd: ['', []],
          oldFundPwd: ['', []],
          newConfirmPwd: ['', [Validators.required, this.confirmationValidator]],
          newPwd: ['', [Validators.required, Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,24}')]],
          oldPwd: ['', [Validators.required, Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,24}')]],
        });
        break;
      case '重置登陆密码':
        this.validateForm = this.fb.group({
          verifyCode: ['', [Validators.required]],
          newConfirmPwd: ['', [Validators.required, this.confirmationValidator]],
          newPwd: ['', [Validators.required, Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,24}')]],
          newConfirmFundPwd: ['', []],
          newFundPwd: ['', []],
          oldPwd: ['', []],
          oldFundPwd: ['', []],
        });
        break;
      case '修改支付密码':
        this.validateForm = this.fb.group({
          verifyCode: ['', []],
          newConfirmPwd: ['', []],
          newPwd: ['', []],
          oldPwd: ['', []],
          newConfirmFundPwd: ['', [Validators.required, this.confirmationFandValidator]],
          newFundPwd: ['', [Validators.required, Validators.pattern('^[0-9]{6}$')]],
          oldFundPwd: ['', [Validators.required, Validators.pattern('^[0-9]{6}$')]],
        });
        break;
      case '重置支付密码':
        this.validateForm = this.fb.group({
          oldFundPwd: ['', []],
          newConfirmPwd: ['', []],
          newPwd: ['', []],
          oldPwd: ['', []],
          verifyCode: ['', [Validators.required]],
          newConfirmFundPwd: ['', [Validators.required, this.confirmationFandValidator]],
          newFundPwd: ['', [Validators.required, Validators.pattern('^[0-9]{6}$')]],
        });
        break;

    };
  };
  handleOk(fromData): void {
    this.isConfirmLoading = true;
    switch (this._selTag.name) {
      case '修改登陆密码':
        this.editPsw(fromData);
        break;
      case '修改支付密码':
        this.editPayPsw(fromData);
        break;
      case '重置登陆密码':
        this.resetPsw(fromData);
        break;
      case '重置支付密码':
        this.resetPayPsw(fromData);
        break;
      case '设置支付密码':
        this.resetPayPsw(fromData);
        break;
    }
  };

  handleCancel(): void {
    this.isVisible = false;
  };
  private _getCaptcha(): void {//发送验证码
    if (this.sendCode()) {
      this.resetPayMsg();
    }

  };




  async resetPayMsg() {
    let obj = { email: null, mobile: null };
    var regExp = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    regExp.test(this._user.loginId) ? obj.email = this._user.loginId : obj.mobile = this._user.loginId;
    let url = this._altTitle == '重置登陆密码' ? '修改登入密码时(未登入) 发送验证码' : '修改交易密码时(已登入) 发送验证码';

    let data = await this._getAJX(url, Object.assign(obj));
    this.api.getData(data, { bool: true, msg: '验证码发送成功，请注意查收。' }) ? null : this.isVisible = this.isConfirmLoading = this._bool;
    this.isConfirmLoading = false;
  };
  async resetPayPsw(tag) {
    delete tag.oldPwd;
    let data = await this._getAJX('[设置交易密码/重置交易密码](已登入) 通过手机验证码', Object.assign(tag));
    this.api.getData(data, { bool: true, msg: '重置交易密码成功！' }) ? this._successOk() : this.isVisible = this.isConfirmLoading = this._bool;
    this.isConfirmLoading = false;

  };
  async resetPsw(tag) {

    let data = await this._getAJX('修改登入密码(已登入) 通过手机验证码', Object.assign(tag));
    this.api.getData(data, { bool: true, msg: '重置登陆密码成功！' }) ? this._successOk() : this.isVisible = this.isConfirmLoading = this._bool;
    this.isConfirmLoading = false;


  };
  async editPsw(tag) {
    let data = await this._getAJX('修改登入密码(已登入)', Object.assign(tag));
    this.api.getData(data, { bool: true, msg: '修改登陆密码成功！' }) ? this._successOk() : this.isVisible = this.isConfirmLoading = this._bool;
    this.isConfirmLoading = false;
  };
  async editPayPsw(tag) {
    let data = await this._getAJX('修改交易密码(已登入)', Object.assign(tag));
    this.api.getData(data, { bool: true, msg: '修改交易密码成功！' }) ? this._successOk() : this.isVisible = this.isConfirmLoading = this._bool;
    this.isConfirmLoading = false;
  };
  private _successOk(): void {
    this.isVisible = this.isConfirmLoading = false;
  };
  private _successListOk(data): void {
    console.log(data)
  };
  private _getAJX(url: string, data: any): any {//接口交換
    let success = this.api.post(urlService('dev', url), data).toPromise();
    return success;
  };

  private sendCode() {
    if (this.captchaLabel === '发送验证码') {
      let num = 60;
      this._timer = setInterval(() => {
        this.captchaLabel = '重新发送(' + num + ')';
        num--;
      }, 1000);
      setTimeout(() => {
        clearInterval(this._timer);
        this.captchaLabel = '发送验证码';
        this._timer = null;
      }, 60 * 1000);
      return true;
    } else {
      return false;
    }
  }

  ngOnDestroy(): void {
    if (this._timer) {
      clearInterval(this._timer);
    }
  }

  constructor(
    private api: ApiService,
    private fb: FormBuilder,
    private modalService: NzModalService,
    private msg: MessageService,
    private token: UserInfoService

  ) {
    this._user = this.token.getUserInfo();
    this.validateForm = this.fb.group({
      verifyCode: ['', []],
      newConfirmPwd: ['', []],
      newPwd: ['', []],
      oldPwd: ['', []],
      newConfirmFundPwd: ['', []],
      newFundPwd: ['', []],
      oldFundPwd: ['', []],
    });
  };
};
